package dk.itu.samd.group2.tagapastry.messages;

import java.io.IOException;
import java.util.Vector;

import rice.p2p.commonapi.Endpoint;
import rice.p2p.commonapi.Id;
import rice.p2p.commonapi.NodeHandle;
import rice.p2p.commonapi.rawserialization.InputBuffer;
import rice.p2p.commonapi.rawserialization.OutputBuffer;
import dk.itu.samd.group2.tagapastry.Index;
import dk.itu.samd.group2.tagapastry.IndexEntry;
import dk.itu.samd.group2.tagapastry.IndexEntryImpl;
import dk.itu.samd.group2.tagapastry.Tag;
import dk.itu.samd.group2.tagapastry.TagapastryImpl;

public class IndexRetractionResponseMsg extends TagapastryMsg {

	public static final short TYPE = 7;
	private static final long serialVersionUID = TYPE;
	private Vector<IndexEntry> entries;
	private char childExtension;
	
	// TODO Consider using NodeHandle for recipient
	// This depends on a security mechanism being implemented
	// if the parent or child drops i.e. churn
	public IndexRetractionResponseMsg(Tag tag, NodeHandle sender, Vector<IndexEntry> entriesVec, char childExtension) {
		super(tag, sender);
		this.entries = entriesVec;
		this.childExtension = childExtension;
	}
	
	public IndexRetractionResponseMsg(InputBuffer buf, Endpoint endpoint) throws IOException {
		super(buf, endpoint);
		this.childExtension = buf.readChar();
		int resultsSize = buf.readInt();
		this.entries = new Vector<IndexEntry>(resultsSize);
		for (int i = 0; i < resultsSize; i++) {
			this.entries.add( new IndexEntryImpl(buf) );
		}
	}
	
	public int getSize() {
		int size = super.getSize() + 1;
		for(IndexEntry ie : entries)
			size += ie.getSize();
		
		return size;
	}

	@Override
	public void execute(TagapastryImpl taga) {
		Index index = taga.getIndex(tag);
		index.handleRetractionResponse(entries, childExtension);
		
		// TODO send msg to child telling that it can delete its entries
		
	}

	@Override
	public short getType() {
		return TYPE;
	}
	
	@Override
	public void serialize(OutputBuffer buf) throws IOException {
		super.serialize(buf);
		buf.writeChar(childExtension);
		buf.writeInt(entries.size());
		for (IndexEntry entry : entries) {
			entry.serialize(buf);
		}
	}
	
	@Override
	public String toString() {
		String str = super.toString();
		str += ", entries: " + entries + " }";
		return str;
	}

	@Override
	public Id getRecepientId() {
		return tag.getId();
	}

}
